package com.huike.web.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.huike.entity.Employee;
import com.huike.query.LoginQuery;
import com.huike.service.EmployeeService;
import com.huike.util.ReturnObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private EmployeeService employeeService;


    @RequestMapping("/login")
    @ResponseBody
    public ReturnObject login(LoginQuery query, HttpSession session) {
        // 1. 实例化时直接添加需加密的数据
        // 2. 先建空md5对象，然后通过.digestHex(data)添加数据
        // 3. 输出时是输出的摘要数据
        Subject currentUser = SecurityUtils.getSubject();
//        String md5Password = SecureUtil.md5(query.getPassword());

        UsernamePasswordToken token =
                new UsernamePasswordToken(query.getUsername(),query.getPassword());
        try {
            currentUser.login(token);
            return new ReturnObject();
        }catch (UnauthenticatedException ue){
            return new ReturnObject().mark("用户名或密码错误");
        }
//        String md5 = SecureUtil.md5("admin1");
//        System.out.println(md5);
//        Employee employee = employeeService.login(query);
//        if (employee !=null){
//            session.setAttribute("user-info",employee.getId());
//            return new ReturnObject();
//        }
//        return new ReturnObject().mark("用户名或密码错误");
    }

    @RequestMapping("/")
    public String index() {
        return "redirect:/login.html";
    }
}
